package com.czy;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class 删除所有权限 {
    private static final List<File> files = new ArrayList<>();

    public static void main(String[] args) throws Exception {
        File file = new File("D:\\project\\dx\\qjkq");
        listFiles(file);
        System.out.println(files);
        System.out.println(files.size());

        for (File f : files) {
            File temporaryFile = new File("d://" + "temp_" + f.getName());
            if (!temporaryFile.exists()) temporaryFile.createNewFile();
            try (BufferedReader br = new BufferedReader(new FileReader(f));
                 BufferedWriter bw = new BufferedWriter(new FileWriter(temporaryFile))) {
                String s;
                while ((s = br.readLine()) != null) {
                    if (!s.contains("@SaCheckPermission(")) {
                        bw.write(s);
                        bw.newLine();
                    }
                }
            }

            // 删除原文件
            if (!f.delete()) throw new IOException("Failed to delete the original file.");
            // 用临时文件替换原文件
            if (!temporaryFile.renameTo(f)) throw new IOException("Failed to replace the original file with the temporary file.");
        }
    }

    // 遍历所有文件
    public static void listFiles(File file) throws Exception {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File file1 : files) {
                listFiles(file1);
            }
        } else {
            if (!file.getName().toLowerCase().endsWith("controller.java")) return;
            try (BufferedReader br = new BufferedReader(new FileReader(file));) {
                String s;
                boolean del = false;
                while ((s = br.readLine()) != null) {
                    if (s.contains("@RestController")) {
                        del = true;
                        break;
                    }
                }
                if (del) files.add(file);
            }
        }
    }

}
